package com.lagou.zookeeperhomework.controller;

import com.alibaba.fastjson.JSON;
import com.lagou.zookeeperhomework.entity.JDBCConfig;
import com.lagou.zookeeperhomework.entity.ZkStrSerializer;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * 定义一个用于修改配置信息的接口
 */
@Controller
@RequestMapping("/config")
@Slf4j
public class configController {

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object service(@RequestBody JDBCConfig jdbcConfig, final HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 获取zkClient对象
        ZkClient zkClient = new ZkClient("linux121:2181,linux122:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        zkClient.writeData("/jdbc", JSON.toJSONString(jdbcConfig));
        log.info("修改数据库连接信息成功：" + jdbcConfig);
        return Collections.singletonMap("message", "修改数据库连接信息成功：" + jdbcConfig);
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Object delete() {
        // 获取zkClient对象
        ZkClient zkClient = new ZkClient("linux121:2181,linux122:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        zkClient.deleteRecursive("/jdbc");
        log.info("数据库连接信息删除成功");
        return Collections.singletonMap("message", "删除数据库连接信息成功");
    }

}
